package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.CartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuPriceVo;
import com.spzx.product.api.service.RemoteProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    //获取向Redis中存放购物车的key
    public String getCartKey(){
        Long userId = SecurityUtils.getUserId();
        return "user:cart:"+userId;
    }

    @Override
    public Boolean addToCart(Long skuId, Integer skuNum) {
        //获取在Redis中保存的购物车的key
        String cartKey = getCartKey();
        //获取购物车中的购物项
        CartInfo  cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey, skuId.toString());

        //判断是否等于null
        if (cartInfo!=null){
            Integer totalCount = cartInfo.getSkuNum() + skuNum;
            //证明原来购物车中已经存在该购物项,只需要获取原来的数量,再加上上传的数量
            cartInfo.setSkuNum(totalCount>99?99:totalCount);
        }else {
            //证明原来购物车中没有存在该购物项,第一次添加
            R<ProductSku> productSkuData = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (R.FAIL==productSkuData.getCode()){
                //远程调用失败
                throw new ServiceException("远程调用微服务根据SkuId查询商品Sku信息失败");
            }
            //获取商品Sku信息
            ProductSku productSku = productSkuData.getData();
             cartInfo = new CartInfo();
             //设置购物项的数量为1
             cartInfo.setSkuNum(skuNum);
             //设置商品的SkuId
            cartInfo.setSkuId(skuId);
            //设置商品的SkuName
            cartInfo.setSkuName(productSku.getSkuName());
            //设置商品的价格
            cartInfo.setCartPrice(productSku.getSalePrice());
            //设置商品的实时价格
            cartInfo.setSkuPrice(productSku.getSalePrice());
            //设置商品的图片
            cartInfo.setThumbImg(productSku.getThumbImg());
        }
        //将商品放入购物车里
        redisTemplate.opsForHash().put(cartKey,skuId.toString(),cartInfo);
        return true;
    }



    @Override
    public List<CartInfo> cartList() {
        //获取购物车里的key
        String cartKey = getCartKey();
        //获取购物车
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);

        cartInfoList.forEach(cartInfo -> {
            R<SkuPriceVo> skuPrice = remoteProductService.getSkuPrice(cartInfo.getSkuId(), SecurityConstants.INNER);
            if (R.fail().equals(skuPrice.getCode())){
                //远程调用失败
                throw new ServiceException("远程调用微服务根据SkuId查询商品skuPrice信息失败");
            }
            //获取skuPrice
            SkuPriceVo skuPriceVo = skuPrice.getData();
            //设置实时价格
            cartInfo.setSkuPrice(skuPriceVo.getSalePrice());
            //获取之后,将修改之后的购物项再设置一遍
            redisTemplate.opsForHash().put(cartKey,skuPriceVo.getSkuId().toString(),cartInfo);
        });
        return cartInfoList;
    }

    @Override
    public void deleteCart(Long skuId) {
        //获取购物车的key
        String cartKey = getCartKey();
        //判断是否过期
        Boolean flag = redisTemplate.opsForHash().hasKey(cartKey, skuId.toString());
        if (flag){
            //根据skuId删除购物车的购物项
            redisTemplate.opsForHash().delete(cartKey,skuId.toString());
        }

    }

    @Override
    public void clearCart() {
        //获取购物车的key
        String cartKey = getCartKey();
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkCart(Long skuId, Integer status) {
        //获取购物车的key
        String cartKey = getCartKey();
        //判断是否有购物项
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(cartKey, skuId.toString());
        if (aBoolean){
            //获取该购物项
            CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey, skuId.toString());
            //设置选择状态
            cartInfo.setIsChecked(status);
            redisTemplate.opsForHash().put(cartKey,skuId.toString(),cartInfo);
        }
    }

    @Override
    public void allCheckCart(Integer status) {
        //获取购物车的key
        String cartKey = getCartKey();
        //获取所有的购物项
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        //验证是否为空
        if (!CollectionUtils.isEmpty(cartInfoList)){
            cartInfoList.forEach(cartInfo -> {
                cartInfo.setIsChecked(status);
                redisTemplate.opsForHash().put(cartKey,String.valueOf(cartInfo.getSkuId()),cartInfo);
            });
        }
    }

    @Override
    public List<CartInfo> getCheckedCartInfo(Long userId) {

       /* //设置向Redis中获取购物车中的key
        String cartKey ="user:cart:"+userId;
        //获取到购物车中所有的购物项
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        //获取被选中的购物项
        List<CartInfo> checkedCartInfoList = cartInfoList.stream().filter(cartInfo -> cartInfo.getIsChecked() == 1).toList();

        return checkedCartInfoList;*/

        //设置向Redis中获取购物车的key
        String cartKey = "user:cart:"+userId;
        //获取购物车中所有的购物项
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        //获取被选中的购物项
        List<CartInfo> checkedCartInfoList = cartInfoList.stream().filter(cartInfo -> cartInfo.getIsChecked() == 1).toList();
        return checkedCartInfoList;
    }

    @Override
    public void chearCheckedCartInfo(Long userId) {
        //设置向Redis中获取购物车的key
        String cartKey = "user:cart:"+userId;
        //获取购物车中所有的购物项
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        //获取被选中的购物项
        List<CartInfo> checkedCartInfoList = cartInfoList.stream().filter(cartInfo -> cartInfo.getIsChecked() == 1).toList();
        //遍历
        checkedCartInfoList.forEach(cartInfo -> {
            //删除购物项
            redisTemplate.opsForHash().delete(cartKey, String.valueOf(cartInfo.getSkuId()));
        });
    }
}
